<?php
/*
 * @package Webhosting Component
 * @copyright Copyright (C) 2007 Jonas Brand. All rights reserved.
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
 * Website: http://wh-com.de
 * Email: info@wh-com.de
 */

/*
* Sicherstellen, dass das Script nicht direkt aufgerufen wird
*/
defined( '_VALID_MOS' ) or die('Direct Access to this acript is not allowed');

/*
* Definition der globalen Variablen
* benoetigt fuer Joomla 1.5 aufgrund beschraenktem Gueltigkeitsbereich
*/
// Objekt-Variablen
global $database, $vhcsdb, $params, $tmpl;
// Parameter
global $mode, $defaultTld, $fields, $adminmail, $componentid, $plantable, $ordertable;
// Joomla-Config
global $mosConfig_mailfrom, $mosConfig_fromname, $mainframe, $my, $Itemid;

if (!defined( '_JEXEC' ))
    session_start();

$catid = (int)mosGetParam($_GET,'catid');
$id    = (int)mosGetParam($_GET, 'id');

// get component id
$query = "SELECT a.id"
. "\n FROM #__components AS a"
. "\n WHERE ( a.admin_menu_link = 'option=com_webhosting' OR a.admin_menu_link = 'option=com_webhosting' )"
. "\n AND a.option = 'com_webhosting'"
;
$database->setQuery( $query );
$comid = $database->loadResult();

// load the row from the db table
$row = new mosComponent( $database );
$row->load( $comid );

define('LANGDIR',$mosConfig_absolute_path."/administrator/components/com_webhosting/language");

if (defined( '_JEXEC' )) {
    $params = JComponentHelper::getParams( 'com_webhosting' );
    if ($catid == 0) $catid = $params->get('catid');
    if ($id == 0) $id = $params->get('planid');
} else {
        $params = new mosParameters( $row->params, $mosConfig_absolute_path.'/administrator/components/com_webhosting/config.xml', 'component' );
}
/*
* Domainklasse laden
*/
include_once($mosConfig_absolute_path."/components/com_webhosting/domain.class.php");

/*
* Modus zum Speichern der Bestellung
* none: Die Daten werden in der Tabelle jos_wh_orders der Joomla-Datenbank gespeichert
* vhcs2: Die Daten werden in einer Vhcs2-Datenbank gespeichert, die unten konfiguriert werden muss
* pd-admin: Die Daten werden in einer PD-Admin-Datenbank gespeichert und eine Domain wird erstellt (noch nicht implementiert)
*/
$mode=$params->get('mode');

/*
* Emailadresse, an die bei Bestellungen eine Email gesendet wird
* Leer lassen, um die in Joomla konfigurierte Emailadresse zu verwenden
*/
$adminmail=$params->get('adminmail');

/*
* Sprachfile laden
* Wenn vorhanden, wird die in Joomla eingestellte Sprache verwendet
* Ansonsten wird Englisch verwendet
*/
$lang=$mainframe->getCfg('lang');
if($lang == 'germani') $lang = 'german';
if(file_exists(LANGDIR.'/'.$lang.".php")) {
    include_once(LANGDIR.'/'.$lang.".php");
} else {
    include_once(LANGDIR.'/'."english.php");
}

/*
* Je nach Modus Datenbank-Objekt setzen und Tabellennamen definieren
*/
$mode=$params->get('mode','joomla');
if($mode=="vhcs2") {
	$vhcsdb = @new database( $params->get('mysql-host'),
							   $params->get('mysql-user'),
							   $params->get('mysql-pass'),
							   $params->get('mysql-db'), '', false );
	$vhcsdb->setQuery("SELECT * FROM hosting_plans LIMIT 1");
	@$vhcsdb->query();
	$error=$vhcsdb->getErrorMsg();
	$vhcsdb->setQuery("SELECT * FROM orders LIMIT 1");
	@$vhcsdb->query();
	$error.=$vhcsdb->getErrorMsg();
	if($error=='')
	{
	    $plantable="hosting_plans";
		$ordertable="orders";
	}
	else
	{
		echo "<div style='text-align:center; color: red; font-size:20px; margin-top:20px;'>".LANG_VHCS_CONNECTION_FAILED."</div>";
		$mode='joomla';
	}
}
if($mode!=="vhcs2") {
    $vhcsdb=$database;
    $plantable="#__wh_plans";
    $ordertable="#__wh_orders";
}

/*
* Standart-Domainendung. Wird in der Auswahlliste ausgewaehlt, wenn vorhanden
*/
$defaultTld=$params->get('defaulttld');

/*
* Felder fuer das Adress-Formular
* Form: 'feldname'->0 (1 fuer Pflichtfeld, 0 fuer optionales Feld)
* Der Feldname wird im Sprachfile angegeben
*/
$fields=array('surname'=>1,'name'=>1,'email'=>1,'company'=>0,'zip'=>1,'city'=>1,'country'=>1,'street'=>1,'tel'=>1,'fax'=>0);

/*
* Templateklasse laden und Template auswaehlen
* Wenn keine Angabe gemacht wurde, wird versucht die in Joomla eingestellte Sprache zu laden
* Ansonsten werden die englischen Templates verwendet
*/
if (defined( '_JEXEC' )) {
    $tmpl = JFactory::getTemplate();
} else {
    require_once( $mosConfig_absolute_path.'/includes/patTemplate/patTemplate.php' );
    $tmpl =& patFactory::createTemplate( '' );
}

$tempdir='components/com_webhosting/templates/';
if($params->get('langtemplate','yes')=='yes') {
    if(file_exists($mosConfig_absolute_path.'/components/com_webhosting/templates/'.$lang.'/overview.html')) {
        $tmpl->setRoot($tempdir.$lang.'/');
    } else {
        $tmpl->setRoot($tempdir.'english/');
    }
}
elseif(file_exists($mosConfig_absolute_path.'/components/com_webhosting/templates/'.$params->get('templatedir').'/overview.html')) {

    $tmpl->setRoot($tempdir.$params->get('templatedir').'/');
}
else {
        $tmpl->setRoot($tempdir.'english/');
}

$task = mosGetParam($_GET,'task');
if ( mosGetParam($_GET, 'view') == 'plan' && $task == '' ) {
    $task = 'details';
}

switch($task) {
case 'details':
    show_details($id);
    break;
case 'domains':
    show_domains($id);
    break;
case 'adress':
     show_adress();
     break;
case 'payment':
	show_payment();
	break;
case 'summary':
     show_summary();
     break;
case 'finish':
    show_finish();
    break;
default:
    show_overview($catid);
    break;
}

/*
* Funktion zur Konvertierung des Preises und optional auch der Waehrung
* @param string $price Preis
* @param string $currency Waehrung (optional)
* @param boolean $standard Standard-Formatierung (fuer Paypal): Dezimaltrennzeichen = Punkt (optional)
* @global object $params Konfiguratins-Parameter
* @global object $database Objekt der Joomla-Datenbank
* @global string $mode Modus zum Speichern der Bestellung (vhcs2 oder none)
*/
function convert_price($price,$currency=false,$standard=false) {
    global $params,$database,$mode;

	// Decimal separator
    if( $params->get('nullpoint','yes')=='no' && $standard == false) {
    	$dec_sep = ',';
    } else {
    	$dec_sep = '.';
    }

    // Thousands separator
    $thousands_sep = '';
    $price = number_format( $price, $params->get('decimalplaces','2'), $dec_sep, $thousands_sep );
    if($standard == true) {
    	return $price;
    } elseif($currency == false) {
        if($mode!=="vhcs2") {
            $id_vhcs=$_SESSION['planid'];
        } else {
            $database->setQuery("SELECT id_vhcs FROM #__wh_plans WHERE id='".$_SESSION['planid']."'");
            $id_vhcs=$database->loadResult();
        }
        $currency=vhcsdb('value',$id_vhcs);
    }

    if(substr_count($currency,'[price]')<>0) {
        $price=str_replace('[price]',$price,$currency);
    } else {
        $price=$price.' '.$currency;
    }

    return $price;
}

/*
* Funktion zum checken einer Email-Adresse auf richtige Syntax und sofern der Parameter aktiv ist auf Erreichbarkeit des Servers
* @param string $email Emailadresse
*/
function check_email($email) {
	global $params;
    if (preg_match("/^[a-z0-9_-]+(\.[a-z0-9_-]+)*@([0-9a-z][0-9a-z-]*[0-9a-z]\.)+([a-z]{2,4}|museum)$/i",$email)==1)
    {
        if($params->get('checkemailhost','no')=='yes') {
			$email2 = explode("@",$email);
			$host = $email2[1];
			$host=$host.".";
			$mxhosts=array();
			if(getmxrr($host, $mxhosts) == TRUE) {
				return true;
			}
			else {
				return false;
			}
		}
		else {
			return true;
		}
    }
    else
    {
		return false;
    }
}

/*
* Funktion zum Ersetzen der in der Datenbank benutzten "Variablen"
* Beispiel: [webspace] wird durch die fuer das Paket festgelegte MB-Zahl ersetzt
* @param string $string Zu ersetzender String
* @param integer $vhcs_id ID des Paketes in der Vhcs-Datenbank
* @param integer $id ID des Paketes in der Joomla-Datenbank
* @global object $database Objekt der Joomla-Datenbank
* @global object $vhcsdb Objekt der Vhcs-Datenbank
* @global string $plantable Name der Vhcs-Tabelle fuer die Angebote
* @global object $params Konfiguratins-Parameter
*/
function replace_variables($string,$vhcs_id,$id)
{
    global $database,$vhcsdb,$plantable,$params;
    $vhcsdb->setQuery("SELECT name,description, props, price, setup_fee, value, payment FROM ".$plantable." WHERE id='".$vhcs_id."' LIMIT 1");
    $plans=$vhcsdb->loadObjectList();
    $plan=$plans[0];
    list($php,$cgi_perl,$subdomains,$aliases,$mailaccounts,$ftpaccounts,$dbaccounts,$dbusers,$traffic,$webspace,$leer)=explode(";", $plan->props);
    $php=="_yes_" ? $php=LANG_YES : $php=LANG_NO;
    $cgi_perl=="_yes_" ? $cgi_perl=LANG_YES : $cgi_perl=LANG_NO;
    $database->setQuery("SELECT domains,tlds FROM #__wh_plans WHERE id='".$id."' LIMIT 1");
    $plans2=$database->loadObjectList();
    $plan2=$plans2[0];
    if($mailaccounts==0) $mailaccounts=LANG_UNLIMITED;
    elseif($mailaccounts==-1) $mailaccounts=0;
    if($subdomains==0) $subdomains=LANG_UNLIMITED;
    elseif($subdomains==-1) $subdomains=0;
    if($ftpaccounts==0) $ftpaccounts=LANG_UNLIMITED;
    elseif($ftpaccounts==-1) $ftpaccounts=0;
    if($aliases==0) $aliases=LANG_UNLIMITED;
    elseif($aliases==-1) $aliases=0;
    if($dbaccounts==0) $dbaccounts=LANG_UNLIMITED;
    elseif($dbaccounts==-1) $dbaccounts=0;
    if($dbusers==0) $dbusers=LANG_UNLIMITED;
    elseif($dbusers==-1) $dbusers=0;
    $replace=array("name"           => $plan->name,
                   "description"    => stripslashes($plan->description),
                   "webspace"       => ($webspace==0 ? LANG_UNLIMITED : $webspace),
                   "webspace-mb"    => ($webspace==0 ? LANG_UNLIMITED : $webspace),
                   "webspace-gb"    => ($webspace==0 ? LANG_UNLIMITED : round($webspace/1024,2)),
                   "traffic"        => ($traffic==0 ? LANG_UNLIMITED : $traffic),
                   "traffic-mb"     => ($traffic==0 ? LANG_UNLIMITED : $traffic),
                   "traffic-gb"     => ($traffic==0 ? LANG_UNLIMITED : round($traffic/1024,2)),
                   "ftpaccounts"    => $ftpaccounts,
                   "mailaccounts"   => $mailaccounts,
                   "subdomains"     => $subdomains,
                   "aliases"        => $aliases,
                   "php"            => $php,
                   "cgi-perl"       => $cgi_perl,
                   "dbaccounts"      => $dbaccounts,
                   "dbusers"        => $dbusers,
                   "price"          => convert_price($plan->price,$plan->value),
                   "price-x6"       => convert_price($plan->price*6,$plan->value),
                   "price-x12"      => convert_price($plan->price*12,$plan->value),
                   "setupfee"       => convert_price($plan->setup_fee,$plan->value),
                   "value"          => $plan->value,
                   "billing_cycle"  => constant('LANG_BILLING_CYCLE_'.$plan->payment),
                   "domains"        => $plan2->domains,
                   "tlds"           => $plan2->tlds
                   );



    foreach($replace as $varname => $value)
    {
        $string=str_replace("[".$varname."]",$value,$string);
    }
    return $string;
}

/*
* Funktion zum Abrufen einzelner Felder aus der Vhcs-Datenbank
* @param string $field Name des Datenbankfeldes
* @param integer $vhcs_id ID des Paketes in der Vhcs-Datenbank
* @global object $vhcsdb Objekt der Vhcs-Datenbank
* @global string $plantable Name der Vhcs-Tabelle fuer die Angebote
* @global object $params Konfiguratins-Parameter
*/
function vhcsdb($field,$vhcs_id)
{
    global $vhcsdb,$plantable,$params;
    $vhcsdb->setQuery("SELECT ".$field." FROM ".$plantable." WHERE id='".$vhcs_id."' LIMIT 1");
    $result=$vhcsdb->loadResult();
    return $result;
}

/*
* Funktion zum Abrufen der Anzahl der Inklusivdomains
* @global object $database Onjekt der Joomla-Datenbank
*/
function get_domainnr()
{
    global $database;
    $planid=$_SESSION['planid'];
    $database->setQuery("SELECT domains FROM #__wh_plans WHERE id='".$planid."'");
    $nr=$database->loadResult();
    return $nr;
}

/*
* Funktion zum Abrufen der Where-Klausel fuer den Abruf der Features
* @param array $features_list Liste der Feature-IDs mit "-" getrennt
* @param string $prefix Prefix der MySQL-Tabelle
*/
function get_where($features_list,$prefix="")
{
    $features=explode("-",$features_list);
    array_shift($features);
    array_pop($features);
    $where='';
    if(in_array('s',$features))
    {
        $where=$prefix."standard='1'";
    }
    elseif(in_array('*',$features))
    {
        $where=$prefix."id=".$prefix."id";
    }
    else
    {
        foreach($features as $id)
        {
            if($where!=="") $where.=",";
            $where.=$id;
        }
        $where=$prefix."id IN (".$where.")";
    }
    return $where;
}

/*
* Funktion zum Abrufen der zur fuer das Paket erlaubten Domainendungen
* @param integer $id ID des Paketes in der Joomla-Datenbank
* @global object $database Objekt der Joomla-Datenbank
* @global string $defaultTld Domainendung, die in der Auswahlliste als Standart ausgewaehlt werden soll
*/
function get_tlds($id)
{
    global $database,$defaultTld;
    $database->setQuery("SELECT domains,tlds FROM #__wh_plans WHERE id='".$id."' LIMIT 1");
    list($plan)=$database->loadObjectList();
    $tlds=explode(",",$plan->tlds);
    $array=array();
    foreach($tlds as $tld)
    {
        if( $tld == trim($defaultTld) )
        $row["selected"]  =  "yes";
        else  $row["selected"]  =  "no";
        $row["tld"]=trim($tld);
        array_push( $array, $row );
    }
    return $array;
}

/*
* Funktion zum Abrufen eines Arrays aller ausgewaehlten Domains mit Berechnung des jeweiligen Preises
* Daten werden fuer Ausgabe vorbereitet
* @global object $database Objekt der Joomla-Datenbank
*/
function get_domains()
{
    global $database;
    $domainnr=get_domainnr();
    if(isset($_SESSION['domains']))
        $domains=$_SESSION['domains'];
    else
        $domains=null;
    for($i=0;$i<$domainnr;$i++)
    {
        if(isset($domains[$i]['domain'])) {
            $domains[$i]['price']=LANG_INCLUSIVE;
	}
    }

    $database->setQuery("SELECT tlds FROM #__wh_plans WHERE id = '".$_SESSION['planid']."' LIMIT 1");
    $plan=$database->loadRow();
    $tlds=explode(',',$plan[0]);

    $n=0;
    while( isset($domains[$n]) ) {
        if(!isset($domains[$n]['price'])) {
            $domains[$n]['price']=convert_price(get_domainprice($domains[$n]['domain']));
	}
	$domainobject = new domain( $domains[$n]['domain'] );
	$tld = $domainobject->get_tld();

	foreach ($tlds as $key => $value) {
		$tlds[$key] = trim($value);
	}
	if( !in_array( $tld, $tlds ) ) {
		array_splice($domains,$n,1);
		$n--;
	}
	$n++;
    }
    return $domains;
}

/*
* Funktion zum Abrufen eines Arrays aller ausgewaehlten Domains mit Berechnung des jeweiligen Preises
* Daten werden fue Weiterverarbeitung vorbereitet
* @global object $database Objekt der Joomla-Datenbank
*/
function get_domainarray()
{
    global $database;
    $domainnr=get_domainnr();
    if(isset($_SESSION['domains']))
	$domains=$_SESSION['domains'];
    else
	$domains=null;
    for($i=0;$i<$domainnr;$i++)
    {
	if(isset($domains[$i]['domain'])) {
	    $domains[$i]['price']=0;
	}
    }

    $database->setQuery("SELECT tlds FROM #__wh_plans WHERE id = '".$_SESSION['planid']."' LIMIT 1");
    $plan=$database->loadRow();
    $tlds=explode(',',$plan[0]);

    $n=0;
    while( isset($domains[$n]) ) {
	if(!isset($domains[$n]['price'])) {
	    $domains[$n]['price']=get_domainprice($domains[$n]['domain']);
	}
    	$domainobject = new domain( $domains[$n]['domain'] );
	$tld = $domainobject->get_tld();

	foreach ($tlds as $key => $value) {
		$tlds[$key] = trim($value);
	}
	if( !in_array( $tld, $tlds ) ) {
		array_splice($domains,$n,1);
		$n--;
	}
	$n++;
    }
    return $domains;
}

/*
* Funktion zur Ermittelung des Domainpreises einer Domain
* @param string $domain Domain
* @global object $database Objekt der Joomla-Datenbank
*/
function get_domainprice($domain) {
    global $database;
    $domain=new domain($domain);
    $domaintld=$domain->get_tld();
    $database->setQuery("SELECT tlds,tldprices FROM #__wh_plans WHERE id = '".$_SESSION['planid']."' LIMIT 1");
    $plan=$database->loadRow();
    $tlds=explode(',',$plan[0]);
    $tldprices=explode(',',$plan[1]);
    $n=0;
    foreach($tlds as $tld) {
        if(chop($tld)==chop($domaintld)) {
            if(isset($tldprices[$n]))
	        $domainprice=$tldprices[$n];
	    else
	        $domainprice=$lastprice;
        }
	if(isset($tldprices[$n]))
	    $lastprice=$tldprices[$n];
        $n++;
    }
    if(!isset($domainprice)) {
        $domainprice = $lastprice;
    }
    return $domainprice;
}

/*
* Funktion zur Pruefung eines mehrdimensionalen Arrays auf das Vorhandensein eines Wertes
* @param string $needle Zu suchender Wert
* @param array $heystack Zu durchsuchendes Array
*/
function in_array_multi($needle, $haystack)
{
    $found = false;
    if( is_array($haystack) ) {
	foreach($haystack as $value)
	    if((is_array($value) && in_array_multi($needle, $value)) || $value == $needle)
		$found = true;
    }
    return $found;
}

/*
* Anzeige der Uebersichtsseite
* Es werden alle Pakete in einer kurzen Uebersicht angezeigt
* @global object $database Objekt der Joomla-Datenbank
* @global object $tmpl Objekt der Template-Engine
* @global integer $Itemid Itemid von Joomla
* @global string $mode Modus zum Speichern der Bestellung (vhcs2 oder none)
* @global object $params Konfiguratins-Parameter
*/
function show_overview( $catid=null )
{
    global $database,$tmpl,$Itemid, $mode, $params;

    if (defined( '_JEXEC' )) $tmpl->readTemplatesFromInput('overview.j15.html');
    else $tmpl->readTemplatesFromInput('overview.html');

	if( (int) $catid > 0 ) {
   		$database->setQuery("SELECT id,id_vhcs,features_short FROM #__wh_plans WHERE published AND catid=".(int)$catid." ORDER BY ordering");
	} else {
    	$database->setQuery("SELECT p.id AS id, p.id_vhcs AS id_vhcs, p.features_short AS features_short ".
    						"FROM #__wh_plans AS p ".
    						"LEFT JOIN #__categories AS c ON c.id = p.catid ".
    						"WHERE p.published = 1 AND (c.published = 1 OR p.catid = 0) ".
    						"ORDER BY c.ordering, p.ordering");
	}
    if(!$plans=$database->loadObjectList()) {
        echo "<center>".LANG_NO_ENTRIES."</center>";
    }
    else {
    $a=count($plans);
    $n=1;
    $b=0;
    foreach($plans as $plan)
    {
        if($mode!=="vhcs2") $plan->id_vhcs=$plan->id;
        $tmpl->clearTemplate("feature");
        $tmpl->addVar('cell','planname',vhcsdb('name',$plan->id_vhcs));
        $tmpl->addVar('cell','description',stripslashes(vhcsdb('description',$plan->id_vhcs)));
        $tmpl->addVar('cell','price',convert_price(vhcsdb('price',$plan->id_vhcs),vhcsdb('value',$plan->id_vhcs)));
        $tmpl->addVar('cell','setupfee',convert_price(vhcsdb('setup_fee',$plan->id_vhcs),vhcsdb('value',$plan->id_vhcs)));
        $tmpl->addVar('cell','id',$plan->id);
        $link = sefRelToAbs( 'index.php?option=com_webhosting&task=details&id='.$plan->id .'&Itemid='. $Itemid );
        $tmpl->addVar('cell','link',$link);
        $where=get_where($plan->features_short,"f.");
        $database->setQuery("SELECT f.title, f.value, f.ordering, c.ordering as catordering FROM #__wh_features as f, #__wh_featurecat as c WHERE f.cat = c.id AND ".$where." ORDER BY c.ordering,f.ordering");
        $features=$database->loadObjectList();
        foreach($features as $feature)
        {
            $tmpl->addVar('feature','feature_title',replace_variables($feature->title,$plan->id_vhcs,$plan->id));
            $tmpl->addVar('feature','feature_value',replace_variables($feature->value,$plan->id_vhcs,$plan->id));
            $tmpl->parseTemplate("feature","a");
        }
        $tmpl->addVar('cell','width',floor(100/$params->get('cols','2')));
        $tmpl->parseTemplate("cell","a");
        if($n%$params->get('cols','2')==0 || $n==$a)
        {
            $tmpl->parseTemplate("row","a");
            $tmpl->clearTemplate("cell");
        }
        $n++;
        $b++;
    }
    $tmpl->displayParsedTemplate('overview');
    }
}

/*
* Anzeige der Detailseite eines Paketes
* @param integer $id ID des anzuzeigenden Paketes
* @global object $database Objekt der Joomla-Datenbank
* @global object $tmpl Objekt der Template-Engine
* @global integer $Itemid Itemid von Joomla
* @global string $mode Modus zum Speichern der Bestellung (vhcs2 oder none)
*/
function show_details($id)
{
    global $database,$tmpl,$Itemid,$mode;
    if (defined( '_JEXEC' )) $tmpl->readTemplatesFromInput('details.j15.html');
    else $tmpl->readTemplatesFromInput('details.html');
    // Abrufen der Paket-Daten
    $database->setQuery("SELECT id,id_vhcs,features FROM #__wh_plans WHERE id='".intval($id)."' AND published='1' LIMIT 1");
    $plans=$database->loadObjectList();
    $plan=$plans[0];
    if($mode!=="vhcs2") $plan->id_vhcs=$plan->id;

    // Vorbereiten der Feature-IDs fuer die Abfragen
    $catwhere=get_where($plan->features,"f.");
    $featurewhere=get_where($plan->features);
   // Kategorien abrufen, die Features enthalten
    $database->setQuery("SELECT c.name as name, c.id as id FROM #__wh_featurecat c, #__wh_features f WHERE f.cat=c.id AND ($catwhere) GROUP BY c.id ORDER BY c.ordering");
    $cats=$database->loadObjectList();
    foreach($cats as $cat)
    {
        $tmpl->addVar('catrow','catname',$cat->name);
        $tmpl->clearTemplate( "row" );
        // Features abrufen
        $database->setQuery("SELECT title,value FROM #__wh_features WHERE cat='".$cat->id."' AND ($featurewhere) ORDER BY ordering");
        $features=$database->loadObjectList();
        foreach($features as $feature)
        {
            $tmpl->addVar('row','feature_title',replace_variables($feature->title,$plan->id_vhcs,$plan->id));
            $tmpl->addVar('row','feature_value',replace_variables($feature->value,$plan->id_vhcs,$plan->id));
            $tmpl->parseTemplate( "row", "a" );
        }
        $tmpl->parseTemplate( "catrow", "a" );
    }
    $tmpl->addVar('details','planname',vhcsdb('name',$plan->id_vhcs));
    $tmpl->addVar('details','description',stripslashes(vhcsdb('description',$plan->id_vhcs)));
    $link = sefRelToAbs( 'index.php?option=com_webhosting&task=domains&id='.$plan->id .'&Itemid='. $Itemid );
    $tmpl->addVar('details','link',$link);
    $tmpl->displayParsedTemplate("details");
}

/*
* Anzeige der Seiten fuer die Domainauswahl
* @param integer $id ID des ausgewaehlten Paketes (nur bei der ersten Auswahl)
* @global object $database Objekt der Joomla-Datenbank
* @global object $tmpl Objekt der Template-Engine
* @global integer $Itemid Itemid von Joomla
* @global string $defaultTld Domainendung, die in der Auswahlliste als Standart ausgewaehlt werden soll
* @global object $params Konfiguratins-Parameter
*/

function show_domains($id)
{
    global $database,$tmpl,$Itemid,$defaultTld,$params;
    if( (int)$id !== 0 ) {
        $_SESSION['planid']=$id;
    }
    elseif(isset($_SESSION['planid']))
        $id=$_SESSION['planid'];
    else
        mosRedirect(html_entity_decode(sefRelToAbs( 'index.php?option=com_webhosting&Itemid='. $Itemid)));

//    if(mosGetParam($_GET,'id') && isset($_SESSION['domains'])) {
//        mosRedirect(html_entity_decode(sefRelToAbs( 'index.php?option=com_webhosting&task=summary&Itemid='. $Itemid)));
//    }
    if (defined( '_JEXEC' )) $tmpl->readTemplatesFromInput('domains.j15.html');
    else $tmpl->readTemplatesFromInput('domains.html');
    $tlds=get_tlds($id);

    if(mosGetParam($_POST, 'firstdomain'))
    {
        $domainname=trim(mosGetParam($_POST,'domain')).".".mosGetParam($_POST,'tld');
        $domain=new domain($domainname);
        if(!mosGetParam($_POST,'domain') || !$domain->is_valid())
        {
            if(!mosGetParam($_POST,'domain'))
                $error=LANG_DOMAIN_NOINPUT;
            else
                $error=LANG_DOMAIN_INVALID1.$domainname.LANG_DOMAIN_INVALID2;
            $tmpl->addRows( "firstdomain_tlds", $tlds );
            $link = sefRelToAbs( 'index.php?option=com_webhosting&task=domains&Itemid='. $Itemid );
            $tmpl->addVar("firstdomain","link",$link);
            $tmpl->addVar("firstdomain_error","error",$error);
            $tmpl->displayParsedTemplate("firstdomain");
        }
        elseif($domain->is_available())
        {
            if(!in_array_multi($domainname,$_SESSION['domains']))
                $_SESSION['domains'][]['domain']=$domainname;
            mosRedirect(html_entity_decode(sefRelToAbs( 'index.php?option=com_webhosting&task=domains&Itemid='.$Itemid)));
        }
        else
        {
            $link = sefRelToAbs( 'index.php?option=com_webhosting&task=domains&Itemid='.$Itemid );
            $tmpl->addVar("notavailable","link",$link);
            $tmpl->addVar("notavailable","domain",$domainname);
            $tmpl->displayParsedTemplate("notavailable");
        }
    }
    elseif(mosGetParam($_POST,'owner_yes'))
    {
        if(!in_array_multi(mosGetParam($_POST,'domain'),$_SESSION['domains']))
            $_SESSION['domains'][]['domain']=mosGetParam($_POST,'domain');
        mosRedirect(html_entity_decode(sefRelToAbs( 'index.php?option=com_webhosting&task=domains&Itemid='.$Itemid)));
    }
    elseif(mosGetParam($_POST,'add'))
    {
        $domainname=mosGetParam($_POST,'domain').".".mosGetParam($_POST,'tld');
        $domain=new domain($domainname);
        if(!mosGetParam($_POST,'domain') || !$domain->is_valid())
        {
            if(!mosGetParam($_POST,'domain'))
                $error=LANG_DOMAIN_NOINPUT;
            else
                $error=LANG_DOMAIN_INVALID1.$domainname.LANG_DOMAIN_INVALID2;
            $tmpl->addRows( "domains",get_domains());
            $tmpl->addRows( "tlds", $tlds );
            $link = sefRelToAbs( 'index.php?option=com_webhosting&task=domains&Itemid='. $Itemid );
            $tmpl->addVar("domainlist","link",$link);
            $tmpl->addVar("error","error",$error);
            $tmpl->addVar("domainlist","domains",get_domainnr());
            $tmpl->displayParsedTemplate("domainlist");
        }
        elseif($domain->is_available())
        {
            if(!in_array_multi($domainname,$_SESSION['domains']))
                $_SESSION['domains'][]['domain']=$domainname;
            mosRedirect(html_entity_decode(sefRelToAbs( 'index.php?option=com_webhosting&task=domains&Itemid='.$Itemid)));
        }
        else
        {
            $link = sefRelToAbs( 'index.php?option=com_webhosting&task=domains&Itemid='.$Itemid );
            $tmpl->addVar("notavailable","link",$link);
            $tmpl->addVar("notavailable","domain",$domainname);
            $tmpl->displayParsedTemplate("notavailable");
        }
    }
    elseif(mosGetParam($_POST,'reset'))
    {
        unset($_SESSION['domains']);
        mosRedirect(html_entity_decode(sefRelToAbs( 'index.php?option=com_webhosting&task=domains&Itemid='.$Itemid)));
    }
    elseif(mosGetParam($_POST,'finish'))
    {
        if(isset($_SESSION['adress'])) {
            mosRedirect(html_entity_decode(sefRelToAbs( 'index.php?option=com_webhosting&task=summary&Itemid='.$Itemid)));
        }
        else {
            mosRedirect(html_entity_decode(sefRelToAbs( 'index.php?option=com_webhosting&task=adress&Itemid='.$Itemid)));
        }
    }
    elseif(isset($_SESSION['domains'][0]['domain']) || $params->get('nodomain','no') == 'yes')
    {
        $tmpl->addRows( "tlds", $tlds );
        $tmpl->addRows( "domains",get_domains());
        $link = sefRelToAbs( 'index.php?option=com_webhosting&task=domains&Itemid='. $Itemid );
        $tmpl->addVar("firstdomain","link",$link);
        $tmpl->addVar("domainlist","domains",get_domainnr());
        $tmpl->displayParsedTemplate("domainlist");
    }
    else
    {
        $tmpl->addRows( "firstdomain_tlds", $tlds );
        $link = sefRelToAbs( 'index.php?option=com_webhosting&task=domains&Itemid='. $Itemid );
        $tmpl->addVar("firstdomain","link",$link);
        $tmpl->displayParsedTemplate("firstdomain");
    }
}

/*
* Anzeige der Seite zur Eingabe der Adressdaten
* @global object $database Objekt der Joomla-Datenbank
* @global object $tmpl Objekt der Template-Engine
* @global integer $Itemid Itemid von Joomla
* @global array $fields Array mit den Feldnamen
*/
function show_adress()
{
    global $database,$tmpl,$Itemid,$fields;
    $error1=0;
    $error2=0;
    if(mosGetParam($_POST,'save'))
    {
        foreach($fields as $field=>$required)
        {
            $value=mosGetParam($_POST,$field);
            if($value=="" && $required==1)
			{
                $error1=1;
				$_SESSION['adress'][$field]=$value;
			}
			elseif($field=='email' && check_email($value) == false)
			{
				$error2=1;
				$_SESSION['adress'][$field]=$value;
			}
            else
            {
                $_SESSION['adress'][$field]=$value;
            }
        }
        if($error1==1) {
            $error=LANG_NOT_ALL_DATA;
		}
		elseif($error2==1) {
			$error=LANG_INVALID_EMAIL;
		}
		else {
			mosRedirect(html_entity_decode(sefRelToAbs( 'index.php?option=com_webhosting&task=payment&Itemid='.$Itemid)));
		}
    }
    if (defined( '_JEXEC' )) $tmpl->readTemplatesFromInput('adress.j15.html');
    else $tmpl->readTemplatesFromInput('adress.html');
    foreach($fields as $field=>$required)
        if(isset($_SESSION['adress'][$field]))
            $tmpl->addVar("adressform",$field,$_SESSION['adress'][$field]);
    $link = sefRelToAbs( 'index.php?option=com_webhosting&task=adress&Itemid='. $Itemid );
    $tmpl->addVar("adressform","link",$link);
    if(isset($error)) $tmpl->addVar("error","error",$error);
    $tmpl->displayParsedTemplate("adressform");
}

/*
* Anzeige der Seite zur Eingabe der Zahlungsinformationen
* @global object $tmpl Objekt der Template-Engine
* @global integer $Itemid Itemid von Joomla
* @global object $params Konfiguratins-Parameter
*/

function show_payment()
{
	global $tmpl, $Itemid, $params;
    if(!mosGetParam($_GET,'edit') && !mosGetParam($_POST, 'save') && isset($_SESSION['payment'])) {
        mosRedirect(html_entity_decode(sefRelToAbs( 'index.php?option=com_webhosting&task=summary&Itemid='. $Itemid)));
    }

	// Wenn keine Zahlungsart erlaubt ist, wird die Seite zur Angabe der Zahlungsinformationen uebersprungen
	if($params->get('bankcol','yes') == 'no' &&
		$params->get('banktrans','no') == 'no' &&
		$params->get('paypal','no') == 'no')
	{
		$_SESSION['payment']['payment'] = 'none';
		mosRedirect(html_entity_decode(sefRelToAbs( 'index.php?option=com_webhosting&task=summary&Itemid='.$Itemid)));
	}
	$error = false;
	if(mosGetParam($_POST, 'save')) {
		// Fehlermeldung
		if(mosGetParam($_POST, 'payment') == 'bankcol' &&
			(mosGetParam($_POST, 'payment_owner') == '' ||
			mosGetParam($_POST, 'payment_code') == '' ||
			mosGetParam($_POST, 'payment_number') == '')) {
			$error=LANG_NOT_ALL_DATA;
		}

		// Speichern
		$_SESSION['payment']['payment']=mosGetParam($_POST, 'payment');
		$_SESSION['payment']['payment_owner']=mosGetParam($_POST, 'payment_owner');
		$_SESSION['payment']['payment_code']=mosGetParam($_POST, 'payment_code');
		$_SESSION['payment']['payment_number']=mosGetParam($_POST, 'payment_number');

		if(!$error) {
			mosRedirect(html_entity_decode(sefRelToAbs( 'index.php?option=com_webhosting&task=summary&Itemid='.$Itemid)));
		}
	}

    if (defined( '_JEXEC' )) $tmpl->readTemplatesFromInput('payment.j15.html');
    else $tmpl->readTemplatesFromInput('payment.html');
	if(isset($_SESSION['payment'])) {
		$payment = $_SESSION['payment']['payment'];
		$owner = $_SESSION['payment']['payment_owner'];
		$number = $_SESSION['payment']['payment_number'];
		$code = $_SESSION['payment']['payment_code'];
	} else {
		$payment = false;
		$owner = false;
		$number = false;
		$code = false;
	}
	if($params->get('bankcol','yes') == 'yes') {
		$tmpl->setAttribute( "bankcol", "visibility", "visible" );
		$tmpl->setAttribute( "bankcol_fields", "visibility", "visible" );
		$tmpl->setAttribute( "bankcol_js", "visibility", "visible" );
		if($payment == 'bankcol') {
			$tmpl->addVar("bankcol","selected"," selected");
			$tmpl->addVar("bankcol_fields","display","table-row");
		}
	}
	if($params->get('banktrans','no') == 'yes') {
		$tmpl->setAttribute( "banktrans", "visibility", "visible" );
		if($payment == 'banktrans') {
			$tmpl->addVar("banktrans","selected"," selected");
			$tmpl->addVar("bankcol_fields","display","none");
		}
	}
	if($params->get('paypal','no') == 'yes') {
		$tmpl->setAttribute( "paypal", "visibility", "visible" );
		if($payment == 'paypal') {
			$tmpl->addVar("paypal","selected"," selected");
			$tmpl->addVar("bankcol_fields","display","none");
		}
	}

	$tmpl->addVar('bankcol_fields','payment_owner',$owner);
	$tmpl->addVar('bankcol_fields','payment_code',$code);
	$tmpl->addVar('bankcol_fields','payment_number',$number);
    $link = sefRelToAbs( 'index.php?option=com_webhosting&task=payment&Itemid='. $Itemid );
    $tmpl->addVar("paymentform","link",$link);
	$tmpl->addVar("error","error",$error);

	$tmpl->displayParsedTemplate("paymentform");
}

/*
* Anzeige der Zusammenfassung der Bestellung
* Es werden Informationen zum Paket, Domains und Adressdaten angezeigt und nocheinmal geprueft
* @global object $database Objekt der Joomla-Datenbank
* @global object $tmpl Objekt der Template-Engine
* @global integer $Itemid Itemid von Joomla
* @global array $fields Array mit den Feldnamen
* @global string $mode Modus zum Speichern der Bestellung (vhcs2 oder none)
* @global object $params Konfiguratins-Parameter
*/

function show_summary($error1=false,$error2=false,$error3=false)
{
    global $database,$tmpl,$Itemid,$fields,$mode,$params;
    if (defined( '_JEXEC' )) $tmpl->readTemplatesFromInput('summary.j15.html');
    else $tmpl->readTemplatesFromInput('summary.html');
    $domainerror=null;
    $adresserror=null;
    $paymenterror=null;
    $planerror=null;
    $noerror=null;
    // Adressdaten
    $n=0;
    foreach($fields as $field=>$required)
    {
        if($_SESSION['adress'][$field]!=="" && isset($_SESSION['adress'][$field])) {
            $adress[$n]['name']=constant("LANG_FIELDS_".strtoupper($field));
            $adress[$n]['value']=$_SESSION['adress'][$field];
			$n++;
        }
        if($required==1 && ($_SESSION['adress'][$field]=="" || !$_SESSION['adress'][$field]))
            $adresserror=LANG_NOT_ALL_DATA;
		if($field=='email' && check_email($_SESSION['adress']['email']) == false) {
            if(!$adresserror) {
				$adresserror=LANG_INVALID_EMAIL;
			}
		}
    }
    $tmpl->addRows("adressrow",$adress);
    $link = sefRelToAbs( 'index.php?option=com_webhosting&task=adress&Itemid='. $Itemid );
    $tmpl->addVar("summary","link_adress",$link);
    // Zahlungsinformationen
    if(!isset($_SESSION['payment']['payment'])) {
    		$paymenterror=LANG_NOT_ALL_DATA;
		$payment = false;

    }
    else {
		$payment = constant('LANG_PAYMENT_'.strtoupper($_SESSION['payment']['payment']));
    }
    if(!isset($_SESSION['payment']['payment_owner'])) {
	   	$owner = false;
		$number = false;
		$code = false;
    }
    else {
		$owner = $_SESSION['payment']['payment_owner'];
		$number = $_SESSION['payment']['payment_number'];
		$code = $_SESSION['payment']['payment_code'];
    }
    $tmpl->addVar("payment","payment",$payment);
    $tmpl->addVar("paymentfields","payment_owner",$owner);
    $tmpl->addVar("paymentfields","payment_code",$code);
    $tmpl->addVar("paymentfields","payment_number",$number);
    if($_SESSION['payment']['payment']=='none') {
    $link = sefRelToAbs( 'index.php?option=com_webhosting&task=summary&Itemid='. $Itemid );
    }
    else {
    $link = sefRelToAbs( 'index.php?option=com_webhosting&task=payment&edit=yes&Itemid='. $Itemid );
    }
    $tmpl->addVar("summary","link_payment",$link);
    // Domains
    $domains=get_domains();
    if(!$domains[0]['domain'] && $params->get('nodomain','no') == 'no')
        $domainerror=LANG_NODOMAIN;
    $tmpl->addRows("domainrow",$domains);
    $link = sefRelToAbs( 'index.php?option=com_webhosting&task=domains&Itemid='. $Itemid );
    $tmpl->addVar("summary","link_domains",$link);
    // Paket
    if($_SESSION['planid'])
    {
        if($mode=="vhcs2") {
            $database->setQuery("SELECT id_vhcs FROM #__wh_plans WHERE id='".intval($_SESSION['planid'])."'");
        }
        else {
            $database->setQuery("SELECT id as id_vhcs FROM #__wh_plans WHERE id='".intval($_SESSION['planid'])."'");
        }
        $id_vhcs=$database->loadResult();
        $tmpl->addVar("plan","name",vhcsdb('name',$id_vhcs));
	$billing_cycle=vhcsdb('payment',$id_vhcs);
	$tmpl->addVar("plan","billing_cycle",constant('LANG_BILLING_CYCLE_'.$billing_cycle));
	$price=vhcsdb('price',$id_vhcs);
	$setupfee=vhcsdb('setup_fee',$id_vhcs);
        $tmpl->addVar('plan','price',convert_price($price));
        $tmpl->addVar('plan','setupfee',convert_price($setupfee));
    }
    else
        $planerror=LANG_NOPLAN;
    // Kosten
    if($_SESSION['planid'])
    {
	// Domains
	$domains=get_domainarray();
	$domainfees = false;
	if($domains) {
            foreach($domains as $domain)
	    {
	        $domainfees+=$domain['price'];
	    }
        }
	if($params->get('domainfees_per_month','no')=='yes' || $params->get('paypal_recurring','no') == 'yes') {
	    $domainfees=($domainfees*$billing_cycle)/12;
	    $months_domains=$billing_cycle;
	} else {
	    $months_domains='12';
	}
	if($months_domains=='1') {
	    $months_domains.=' '.LANG_MONTH;
	} else {
	    $months_domains.=' '.LANG_MONTHS;
	}
	$tmpl->addVar('fees','domains',convert_price($domainfees));
	$tmpl->addVar('fees','months_domains',$months_domains);
	// Einrichtungsgebuehr
	$tmpl->addVar('fees','setup_fee',convert_price($setupfee));
	// Paket
	$planfee=$price*$billing_cycle;
	$tmpl->addVar('fees','plan',convert_price($planfee));
	if($billing_cycle=='1') {
	    $months_plan=$billing_cycle.' '.LANG_MONTH;
	} else {
	    $months_plan=$billing_cycle.' '.LANG_MONTHS;
	}
	$tmpl->addVar('fees','months_plan',$months_plan);
	// Gesamt
	$totalfee=$domainfees+$planfee+$setupfee;
	$tmpl->addVar('fees','total',convert_price($totalfee));
    }

    if($params->get('overview-page','no')=="yes") {
        $link = sefRelToAbs( $params->get('overview-link') );
    }
    else {
        $link = sefRelToAbs( 'index.php?option=com_webhosting&Itemid='. $Itemid );
    }
    $tmpl->addVar("summary","link_plan",$link);
	if($error1==1)
		$checkbox1='<span style="color:red; font-weight:bold;">'.$params->get('checkbox1').'</span>';
	else
		$checkbox1=$params->get('checkbox1');
	if($error2==1)
		$checkbox2='<span style="color:red; font-weight:bold;">'.$params->get('checkbox2').'</span>';
	else
		$checkbox2=$params->get('checkbox2');
	if($error3==1)
		$checkbox3='<span style="color:red">'.$params->get('checkbox3').'</span>';
	else
		$checkbox3=$params->get('checkbox3');

	$tmpl->addRows('checkbox',array(array('num'=>1,'title'=>$checkbox1),array('num'=>2,'title'=>$checkbox2),array('num'=>3,'title'=>$checkbox3)));

    // Submit-Button anzeigen
    if(!$domainerror && !$adresserror && !$planerror && !$paymenterror)
        $noerror=1;
    $link = sefRelToAbs( 'index.php?option=com_webhosting&task=finish&Itemid='. $Itemid );
    $tmpl->addVar("summary","link",$link);

    $tmpl->addVar("adresserror","error",$adresserror);
    $tmpl->addVar("paymenterror","error",$paymenterror);
    $tmpl->addVar("domainerror","error",$domainerror);
    $tmpl->addVar("planerror","error",$planerror);
    $tmpl->addVar("submit","noerror",$noerror);
    $tmpl->displayParsedTemplate("summary");
}

/*
* Abschluss der Bestellung und Speicherung der Daten
* Daten speichern, Emails verschicken, Bestaetigungsseite anzeigen
* @global object $vhcsdb Objekt der Vhcs-Datenbank
* @global object $database Objekt der Joomla-Datenbank
* @global object $tmpl Objekt der Template-Engine
* @global integer $Itemid Itemid von Joomla
* @global string $mosConfig_mailfrom Konfigurierte Abesender-Emailadresse
* @global string $mosConfig_fromname Konfigurierter Absender-Name
* @global array $fields Array mit den Feldnamen
* @global string $plantable Name der Vhcs-Tabelle fuer die Angebote
* @global string $ordertable Name der Vhcs-Tabelle fuer die Bestellungen
* @global string $mode Modus zum Speichern der Bestellung (vhcs2 oder none)
* @global string $adminmail Emailadresse, an die bei Bestellungen eine Email gesendet wird
* @global object $params Konfigurations-Parameter
*/
function show_finish()
{
    global $vhcsdb,$database,$tmpl,$Itemid,$mosConfig_mailfrom,$mosConfig_fromname,$fields,$plantable,$ordertable,$mode,$adminmail,$params;

	if(((!mosGetParam($_POST,'checkbox1') && $params->get('checkbox1')!=='') ||
	   (!mosGetParam($_POST,'checkbox2') && $params->get('checkbox2')!=='') ||
	   (!mosGetParam($_POST,'checkbox3') && $params->get('checkbox3')!=='')) &&
	   mosGetParam($_POST,'finish') &&
	   isset($_SESSION['planid']))
	{
		if(!mosGetParam($_POST,'checkbox1') && $params->get('checkbox1')!=='')
			$error1=1;
		else
			$error1=false;
		if(!mosGetParam($_POST,'checkbox2') && $params->get('checkbox2')!=='')
			$error2=1;
		else
			$error2=false;
		if(!mosGetParam($_POST,'checkbox3') && $params->get('checkbox3')!=='')
			$error3=1;
		else
			$error3=false;
		show_summary($error1,$error2,$error3);
	}
    elseif(mosGetParam($_POST,'finish') && isset($_SESSION['planid']))
    {
        // Get vhcs id
        if($mode=="vhcs2") {
            $database->setQuery("SELECT id_vhcs, features_short FROM #__wh_plans WHERE id='".intval($_SESSION['planid'])."' LIMIT 1");
        }
        else {
            $database->setQuery("SELECT id as id_vhcs, features_short FROM #__wh_plans WHERE id='".intval($_SESSION['planid'])."' LIMIT 1");
        }
	$database->loadObject($jplan);
        $vhcs_id=$jplan->id_vhcs;
        // Get reseller id
        if($mode=="vhcs2") {
            $vhcsdb->setQuery("SELECT reseller_id FROM ".$plantable." WHERE id='".$vhcs_id."' LIMIT 1");
            $resellerid=$vhcsdb->loadResult();
        } else {
	    $resellerid=0;
	}

        // Get data
        $vhcsdb->setQuery("SELECT name, props, price, setup_fee, payment, value FROM ".$plantable." WHERE id='".$vhcs_id."' LIMIT 1");
        $vhcsdb->loadObject($plan);

        // Calculate Fees
	// Domains
        $setupfee=$plan->setup_fee;
        $billing_cycle=$plan->payment;
	$domains=get_domainarray();
	$domainfees = '';
	foreach($domains as $domain) {
	    $domainfees+=$domain['price'];
	}
    	if($params->get('domainfees_per_month','no')=='yes' || $params->get('paypal_recurring','no') == 'yes') {
    	    $domainfees=($domainfees*$billing_cycle)/12;
    	    $months_domains=$billing_cycle;
    	} else {
    	    $months_domains='12';
    	}
    	if($months_domains=='1') {
    	    $months_domains.=' '.LANG_MONTH;
    	} else {
    	    $months_domains.=' '.LANG_MONTHS;
	    }
    	// Paket
	    $planfee=$plan->price*$billing_cycle;
	    if($billing_cycle=='1') {
	        $months_plan=$billing_cycle.' '.LANG_MONTH;
	    } else {
	        $months_plan=$billing_cycle.' '.LANG_MONTHS;
    	}
	    // Gesamt
	    $totalfee=$domainfees+$planfee+$setupfee;

        // Save order
        $customerid="";
        $date=time();
        $vhcsdb->setQuery("INSERT INTO ".$ordertable." (
                            user_id,
                            plan_id,
                            date,
                            domain_name,
                            customer_id,
                            fname,
                            lname,
                            firm,
                            zip,
                            city,
                            country,
                            email,
                            phone,
                            fax,
                            street1,
                            street2,
                            status)
                           VALUES('".
                            $resellerid."','".
                            $vhcs_id."','".
                            $date."','".
                            $_SESSION['domains'][0]['domain']."','".
                            $customerid."','".
                            $_SESSION['adress']['surname']."','".
                            $_SESSION['adress']['name']."','".
                            $_SESSION['adress']['company']."','".
                            $_SESSION['adress']['zip']."','".
                            $_SESSION['adress']['city']."','".
                            $_SESSION['adress']['country']."','".
                            $_SESSION['adress']['email']."','".
                            $_SESSION['adress']['tel']."','".
                            $_SESSION['adress']['fax']."','".
                            $_SESSION['adress']['street']."','".
                            sprintf("%01.".$params->get('decimalplaces','2')."f", $totalfee)."','".
                            "new')");
        $vhcsdb->query() or die("<center>MySQL error</center>");
        $vhcsdb->setQuery("SELECT id FROM ".$ordertable." WHERE date='".$date."' AND domain_name='".$_SESSION['domains'][0]['domain']."' LIMIT 1");
        $orderid=$vhcsdb->loadResult();
	// Prepare feature list
        $where=get_where($jplan->features_short,"f.");
        $database->setQuery("SELECT f.title, f.value, f.ordering, c.ordering as catordering FROM #__wh_features as f, #__wh_featurecat as c WHERE f.cat = c.id AND ".$where." ORDER BY c.ordering,f.ordering");
        $features=$database->loadObjectList();
	$featurelist = '';
        foreach($features as $feature)
        {
            $featurelist .= html_entity_decode(replace_variables($feature->title,$vhcs_id,$vhcs_id));
	    $featurelist .= ': ';
            $featurelist .= html_entity_decode(replace_variables($feature->value,$vhcs_id,$vhcs_id));
	    $featurelist .= "\n";
        }
        // Prepare lists of domains
        $domains=get_domains();
        $domainlist='';
        foreach($domains as $domain) {
            if( $domainlist != '' )
                $domainlist.="\n";
            $domainlist.=$domain['domain'];
            $domainlist.=' - '.$domain['price'];
	        $domainobject=new domain($domain['domain']);
	        if($domainobject->is_available() === false) {
                 $domainlist.= ' '.LANG_DOMAIN_TRANSFER;
            }
        }

        // Prepare adress data
        $n=0;
	$adressdata='';
        foreach($fields as $field=>$required)
        {
            if($_SESSION['adress'][$field]!=="")
            {
                if(isset($adressdata))
                    $adressdata.="\n";
                $adressdata.=constant("LANG_FIELDS_".strtoupper($field));
                $adressdata.=": ";
                $adressdata.=$_SESSION['adress'][$field];
            }
        }
        // Prepare Payment data
        $payment = constant('LANG_PAYMENT_'.strtoupper($_SESSION['payment']['payment']));
        $paymentdata=LANG_PAYMENT.": ".$payment;
        $paymentsubject=sprintf(LANG_PAYMENT_SUBJECTSTRING, $orderid,$plan->name);
        if($_SESSION['payment']['payment']=='bankcol') {
        	$paymentdata.="\n";
        	$paymentdata.=LANG_PAYMENT_OWNER.': '.$_SESSION['payment']['payment_owner']."\n";
        	$paymentdata.=LANG_PAYMENT_CODE.': '.$_SESSION['payment']['payment_code']."\n";
        	$paymentdata.=LANG_PAYMENT_NUMBER.': '.$_SESSION['payment']['payment_number'];
        }
        elseif($_SESSION['payment']['payment']=='banktrans') {
		$paymentdata.="\n";
        	$paymentdata.=LANG_PAYMENT_SUBJECT.': '.$paymentsubject;
        }
	elseif($_SESSION['payment']['payment']=='paypal' && $params->get('paypal_recurring','no') == 'yes') {
                switch ($billing_cycle) {
                case 1:
                    $period=1;
                    $unit='M';
                    break;
                case 3:
                    $period=3;
                    $unit='M';
                    break;
                case 6:
                    $period=6;
                    $unit='M';
                    break;
                case 12:
                    $period=1;
                    $unit='Y';
                    break;
                case 24:
                    $period=2;
                    $unit='Y';
                }
		$paymentdata.="\n";
		$paymentdata.=LANG_PAYMENT_PAYPALLINK.': https://www.paypal.com/cgi-bin/webscr?cmd=_xclick-subscriptions&business='.urlencode($params->get('paypal_adress')).'&item_name='.urlencode(sprintf(LANG_PAYMENT_SUBJECTSTRING,$orderid)).'&a1='.convert_price($totalfee,false,true).'&t1='.$unit.'&p1='.$period.'&a3='.convert_price($domainfees+$planfee,false,true).'&t3='.$unit.'&p3='.$period.'&src=1&no_shipping=1&no_note=1&currency_code='.urlencode($params->get('paypal_currency','EUR')).'&bn=PP%2dBuyNowBF';
		$_SESSION['paymentsubject']=$paymentsubject;
		$_SESSION['period']=$period;
		$_SESSION['unit']=$unit;
		$_SESSION['firstamount']=convert_price($totalfee,false,true);
		$_SESSION['recurringamount']=convert_price($domainfees+$planfee,false,true);
	}
	elseif($_SESSION['payment']['payment']=='paypal' && $params->get('paypal_recurring','no') == 'no') {
		$paymentdata.="\n";
		$paymentdata.=LANG_PAYMENT_PAYPALLINK.': https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business='.urlencode($params->get('paypal_adress')).'&item_name='.urlencode(sprintf(LANG_PAYMENT_SUBJECTSTRING,$orderid)).'&amount='.convert_price($totalfee,false,true).'&no_shipping=1&no_note=1&currency_code='.urlencode($params->get('paypal_currency','EUR')).'&bn=PP%2dBuyNowBF';
		$_SESSION['paymentsubject']=$paymentsubject;
		$_SESSION['amount']=convert_price($totalfee,false,true);
	}
	// Prepare and Send Emails
	if($params->get('terminfo','no')=='yes') {
            $adminterms = "\n".sprintf(LANG_EMAIL_TO_ADMIN_TERMS,
                                 $_SESSION['adress']['surname'].' '.$_SESSION['adress']['name'],
                                 date("d.m.Y"),
                                 date("H:i"),
                                 $_SERVER['REMOTE_ADDR'])."\n";
        } else {
            $adminterms = '';
        }
        $adminmessage = sprintf (LANG_EMAIL_TO_ADMIN,
                                $adminterms,
                                $orderid,
                                $plan->name,
                                constant('LANG_BILLING_CYCLE_'.$billing_cycle),
                                $months_domains,
                                convert_price($domainfees),
                                convert_price($setupfee),
                                $months_plan,
                                convert_price($planfee),
                                convert_price($totalfee),
                                $domainlist,
                                $adressdata,
                                $paymentdata,
                                $featurelist
                                );
        if($adminmail=="" || !isset($adminmail)) {
            $adminmail=$mosConfig_mailfrom;
            }
        $adminsubject=LANG_EMAIL_TO_ADMIN_SUBJECT;
        mosMail($mosConfig_mailfrom, $mosConfig_fromname, $adminmail, $adminsubject, $adminmessage);
        if($params->get('terminfo','no')=='yes') {
            $customerterms="\n".sprintf(LANG_EMAIL_TO_CUSTOMER_TERMS,
                                  date("d.m.Y"),
                                  date("H:i"),
                                  $_SERVER['REMOTE_ADDR'])."\n";
        } else {
            $customerterms='';
        }
        $customermessage = sprintf (LANG_EMAIL_TO_CUSTOMER,
                                $_SESSION['adress']['surname'],
                                $_SESSION['adress']['name'],
                                $customerterms,
                                $orderid,
                                $plan->name,
                                constant('LANG_BILLING_CYCLE_'.$billing_cycle),
                                $months_domains,
                                convert_price($domainfees),
                                convert_price($setupfee),
                                $months_plan,
                                convert_price($planfee),
                                convert_price($totalfee),
                                $domainlist,
                                $adressdata,
                                $paymentdata,
				$featurelist
                                );
        $customermail=$_SESSION['adress']['email'];
        $customersubject=LANG_EMAIL_TO_CUSTOMER_SUBJECT;
        mosMail($mosConfig_mailfrom, $mosConfig_fromname, $customermail, $customersubject, $customermessage);
        unset($_SESSION['domains']);
        unset($_SESSION['adress']);
        unset($_SESSION['planid']);
        unset($_SESSION['payment']);
        mosRedirect(html_entity_decode(sefRelToAbs( 'index.php?option=com_webhosting&task=finish&Itemid='. $Itemid )));
    }
    else
    {
    if (defined( '_JEXEC' )) $tmpl->readTemplatesFromInput('finished.j15.html');
    else $tmpl->readTemplatesFromInput('finished.html');
	$link = sefRelToAbs( 'index.php' );
	$tmpl->addVar("finished","link",$link);
	if(isset($_SESSION['paymentsubject'])) {
            if( isset( $_SESSION['period'] ) ) {
                $tmpl->addVar("paypal_recurring","firstamount",$_SESSION['firstamount']);
                $tmpl->addVar("paypal_recurring","recurringamount",$_SESSION['recurringamount']);
                $tmpl->addVar("paypal_recurring","period",$_SESSION['period']);
                $tmpl->addVar("paypal_recurring","unit",$_SESSION['unit']);
                $tmpl->addVar("paypal_recurring","subject",$_SESSION['paymentsubject']);
                $tmpl->addVar("paypal_recurring","currency",$params->get('paypal_currency','EUR'));
                $tmpl->addVar("paypal_recurring","adress",$params->get('paypal_adress'));
                unset($_SESSION['firstamount']);
                unset($_SESSION['recurringamount']);
                unset($_SESSION['period']);
                unset($_SESSION['unit']);
            	unset($_SESSION['paymentsubject']);
                unset($_SESSION['paypal_currency']);
                unset($_SESSION['paypal_adress']);
            }
            else {
                $tmpl->addVar("paypal","subject",$_SESSION['paymentsubject']);
                $tmpl->addVar("paypal","currency",$params->get('paypal_currency','EUR'));
                $tmpl->addVar("paypal","adress",$params->get('paypal_adress'));
                $tmpl->addVar("paypal","amount",$_SESSION['amount']);
                unset($_SESSION['paymentsubject']);
                unset($_SESSION['paypal_currency']);
                unset($_SESSION['paypal_adress']);
                unset($_SESSION['amount']);
            }
	}
        $tmpl->displayParsedTemplate("finished");
    }
}
?>
